﻿using Microsoft.Extensions.Configuration;
using Serilog;
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;

namespace Helpers
{
    /// <summary>
    /// mq默认配置
    /// </summary>
    public static class MqGlobleConfig
    {
        /// <summary>
        /// 服务质量保证指定最大的unacked messages数目
        /// </summary>
        public static uint PrefetchSize { get; } = 0;
        /// <summary>
        /// true\false 是否将上面设置应用于channel，简单点说，就是上面限制是channel级别的还是consumer级别
        /// </summary>
        public static bool Global { get; } = false;
        public static MqConfig DefaultMQConfig { get; private set; }
        /// <summary>
        /// 默认虚拟机
        /// </summary>
        public static string VHost { get; private set; }
        /// <summary>
        /// 默认交换机
        /// </summary>
        public static string Exchange { get; private set; }
        /// <summary>
        /// 在no_ask=false的情况下生效，即在自动应答的情况下这两个值是不生效的
        /// </summary>
        public static ushort PrefetchCount => DefaultMQConfig.PrefetchCount ?? 1;
        /// <summary>
        /// 是否持久化
        /// </summary>
        public static bool Durable => DefaultMQConfig.Durable;
        /// <summary>
        /// 是否自动应答
        /// </summary>
        public static bool AutoAck => DefaultMQConfig.AutoAck;
        /// <summary>
        /// 用户名
        /// </summary>
        public static string UserName => DefaultMQConfig.UserName;
        /// <summary>
        /// 密码
        /// </summary>
        public static string Password => DefaultMQConfig.Password;
        public static bool IsDebug => DefaultMQConfig.IsDebug;

        /// <summary>
        /// 初始化mq
        /// </summary>
        /// <param name="configuration"></param>
        public static void InitDefaultConnection(IConfiguration configuration) => InitDefaultConnection(configuration.GetSection("mq").Get<MqConfig>());

        public static void InitDefaultConnection(MqConfig mqConfig, string vHost, string exchange)
        {
            mqConfig.vHost = vHost;
            mqConfig.ExchangeName = exchange;
            InitDefaultConnection(mqConfig);
        }

        public static void InitDefaultConnection(MqConfig mqConfig)
        {
            DefaultMQConfig = mqConfig ?? throw new ArgumentNullException(nameof(mqConfig));
            VHost = mqConfig.vHost;
            Exchange = mqConfig.ExchangeName;
            Log.Information($"mq配置信息--{JsonConvert.SerializeObject(mqConfig)}");
        }
    }
}
